import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * 绘图功能状态管理
 */
export const useDrawStore = defineStore('draw', () => {
  // 状态
  const isDrawing = ref(false)
  const isIconDrawing = ref(false)
  const isDelete = ref(false)
  const isModify = ref(false)
  const selectedShape = ref('Polygon')
  const selectedIcon = ref('destination')
  const scale = ref(0.1)
  const drawHook = ref(null)
  const isMapReady = ref(false)
  
  // 形状选项
  const shapeOptions = ref([
    { type: 'Polygon', icon: 'EditPen', name: '多边形' },
    { type: 'Circle', icon: 'EditPen', name: '圆形' },
    { type: 'LineString', icon: 'EditPen', name: '线段' },
    { type: 'Point', icon: 'Location', name: '点(红色)' },
    { type: 'Point-Blue', icon: 'Location', name: '点(蓝色)' },
    { type: 'Point-Green', icon: 'Location', name: '点(绿色)' },
    { type: 'Point-Yellow', icon: 'Location', name: '点(黄色)' }
  ])
  
  // 图标选项
  const iconOptions = ref([
    { type: 'destination', name: '目的地' },
    { type: 'icon', name: '图标' }
  ])
  
  // 计算属性
  const canSelectShape = computed(() => {
    return isMapReady.value
  })
  
  const canDraw = computed(() => {
    return isMapReady.value && !!selectedShape.value
  })
  
  // 方法
  /**
   * 设置绘图钩子
   * @param {Object} hook - 绘图钩子对象
   */
  function setDrawHook(hook) {
    drawHook.value = hook
    
    // 同步状态
    if (hook) {
      isDrawing.value = hook.isDrawing?.value || false
      isIconDrawing.value = hook.isIconDrawing?.value || false
      isDelete.value = hook.isDelete?.value || false
      isModify.value = hook.isModify?.value || false
      
      // 同步选项
      if (hook.shapeOptions && hook.shapeOptions.length > 0) {
        shapeOptions.value = hook.shapeOptions
      }
      
      if (hook.iconOptions && hook.iconOptions.length > 0) {
        iconOptions.value = hook.iconOptions
      }
    }
  }
  
  /**
   * 设置地图就绪状态
   * @param {Boolean} status - 就绪状态
   */
  function setMapReady(status) {
    isMapReady.value = status
  }
  
  /**
   * 设置绘制状态
   * @param {Boolean} status - 绘制状态
   */
  function setDrawing(status) {
    // 如果开启绘制状态，先关闭删除和编辑状态
    if (status) {
      if (isDelete.value) {
        setDelete(false);
      }
      if (isModify.value) {
        setModify(false);
      }
    }
    
    isDrawing.value = status;
    if (drawHook.value?.isDrawing && typeof drawHook.value.isDrawing === 'object' && 'value' in drawHook.value.isDrawing) {
      drawHook.value.isDrawing.value = status;
    }
  }
  
  /**
   * 设置删除状态
   * @param {Boolean} status - 删除状态
   */
  function setDelete(status) {
    // 如果开启删除状态，先关闭绘制和编辑状态
    if (status) {
      if (isDrawing.value) {
        setDrawing(false);
      }
      if (isModify.value) {
        setModify(false);
      }
    }
    
    isDelete.value = status;
    if (drawHook.value?.isDelete && typeof drawHook.value.isDelete === 'object' && 'value' in drawHook.value.isDelete) {
      drawHook.value.isDelete.value = status;
    }
  }
  
  /**
   * 设置编辑状态
   * @param {Boolean} status - 编辑状态
   */
  function setModify(status) {
    // 如果开启编辑状态，先关闭绘制和删除状态
    if (status) {
      if (isDrawing.value) {
        setDrawing(false);
      }
      if (isDelete.value) {
        setDelete(false);
      }
    }
    
    isModify.value = status;
    if (drawHook.value?.isModify && typeof drawHook.value.isModify === 'object' && 'value' in drawHook.value.isModify) {
      drawHook.value.isModify.value = status;
    }
  }
  
  /**
   * 设置选中的形状
   * @param {String} shape - 形状类型
   */
  function setSelectedShape(shape) {
    selectedShape.value = shape
  }
  
  /**
   * 设置选中的图标
   * @param {String} icon - 图标类型
   */
  function setSelectedIcon(icon) {
    selectedIcon.value = icon
  }
  
  /**
   * 调整图标大小
   * @param {Number} delta - 调整值
   */
  function adjustIconScale(delta) {
    if (drawHook.value && drawHook.value.adjustIconScale) {
      drawHook.value.adjustIconScale(delta)
    }
  }
  
  /**
   * 开始绘制形状
   */
  function startDrawShape() {
    if (!drawHook.value || !drawHook.value.drawShape) {
      ElMessage.warning('绘图工具未准备就绪');
      return;
    }
    
    try {
      // 先关闭所有其他状态
      if (isDelete.value) {
        setDelete(false);
      }
      if (isModify.value) {
        setModify(false);
      }
      
      // 设置绘制状态
      setDrawing(true);
      
      // 开始绘制
      drawHook.value.drawShape(selectedShape.value);
    } catch (error) {
      console.error('绘制形状失败:', error);
      setDrawing(false);
      ElMessage.error('绘制失败: ' + (error.message || '未知错误'));
    }
  }
  
  /**
   * 开始绘制图标
   */
  function startDrawIcon() {
    if (!drawHook.value || !drawHook.value.startDrawIcon) {
      ElMessage.warning('绘图工具未准备就绪');
      return;
    }
    
    try {
      // 先关闭所有其他状态
      if (isDelete.value) {
        setDelete(false);
      }
      if (isModify.value) {
        setModify(false);
      }
      if (isDrawing.value) {
        setDrawing(false);
      }
      
      // 如果当前正在绘制图标，先清除绘制交互
      if (isIconDrawing.value && drawHook.value.clearInteractions) {
        console.log('清除当前图标绘制交互');
        drawHook.value.clearInteractions();
      }
      
      // 设置图标绘制状态
      isIconDrawing.value = true;
      if (drawHook.value?.isIconDrawing && typeof drawHook.value.isIconDrawing === 'object' && 'value' in drawHook.value.isIconDrawing) {
        drawHook.value.isIconDrawing.value = true;
      }
      
      // 开始绘制
      drawHook.value.startDrawIcon(selectedIcon.value);
      
      // 添加调试日志
      console.log('图标绘制已启动:', {
        'store状态-图标绘制': isIconDrawing.value,
        'store状态-图形绘制': isDrawing.value,
        'store状态-删除': isDelete.value,
        'store状态-编辑': isModify.value,
        'hook状态-图标绘制': drawHook.value.isIconDrawing?.value,
        'hook状态-图形绘制': drawHook.value.isDrawing?.value,
        'hook状态-删除': drawHook.value.isDelete?.value,
        'hook状态-编辑': drawHook.value.isModify?.value
      });
    } catch (error) {
      console.error('添加图标失败:', error);
      isIconDrawing.value = false;
      if (drawHook.value?.isIconDrawing && typeof drawHook.value.isIconDrawing === 'object' && 'value' in drawHook.value.isIconDrawing) {
        drawHook.value.isIconDrawing.value = false;
      }
      ElMessage.error('添加图标失败: ' + error.message);
    }
  }
  
  /**
   * 切换删除状态
   * @param {Boolean} val - 删除状态
   */
  function toggleDelete(val) {
    console.log('store中切换删除状态:', val);
    
    // 如果要开启删除模式，先关闭所有其他模式
    if (val) {
      if (isDrawing.value) {
        setDrawing(false);
      }
      if (isModify.value) {
        setModify(false);
      }
    }
    
    // 更新本地状态
    setDelete(val);
    
    if (!drawHook.value) {
      console.warn('drawHook未初始化，无法切换删除状态');
      return;
    }
    
    try {
      if (val) {
        console.log('初始化删除交互');
        drawHook.value.initDeleteInteraction();
      } else if (drawHook.value.clearInteractions) {
        console.log('清除交互');
        drawHook.value.clearInteractions();
      }
      
      console.log('删除状态切换完成:', {
        'store状态-删除': isDelete.value,
        'store状态-编辑': isModify.value,
        'store状态-绘制': isDrawing.value,
        'hook状态-删除': drawHook.value.isDelete?.value,
        'hook状态-编辑': drawHook.value.isModify?.value,
        'hook状态-绘制': drawHook.value.isDrawing?.value
      });
    } catch (error) {
      console.error('切换删除状态失败:', error);
      // 发生错误时恢复状态
      setDelete(!val);
    }
  }
  
  /**
   * 切换编辑状态
   * @param {Boolean} val - 编辑状态
   */
  function toggleModify(val) {
    console.log('store中切换编辑状态:', val);
    
    // 如果要开启编辑模式，先关闭所有其他模式
    if (val) {
      if (isDrawing.value) {
        setDrawing(false);
      }
      if (isDelete.value) {
        setDelete(false);
      }
    }
    
    // 更新本地状态
    setModify(val);
    
    if (!drawHook.value) {
      console.warn('drawHook未初始化，无法切换编辑状态');
      return;
    }
    
    try {
      if (val) {
        console.log('初始化编辑交互');
        drawHook.value.initModifyInteraction();
      } else if (drawHook.value.clearInteractions) {
        console.log('清除交互');
        drawHook.value.clearInteractions();
      }
      
      console.log('编辑状态切换完成:', {
        'store状态-编辑': isModify.value,
        'store状态-删除': isDelete.value,
        'store状态-绘制': isDrawing.value,
        'hook状态-编辑': drawHook.value.isModify?.value,
        'hook状态-删除': drawHook.value.isDelete?.value,
        'hook状态-绘制': drawHook.value.isDrawing?.value
      });
    } catch (error) {
      console.error('切换编辑状态失败:', error);
      // 发生错误时恢复状态
      setModify(!val);
    }
  }
  
  /**
   * 保存绘制
   */
  function saveDrawings() {
    if (!drawHook.value || !drawHook.value.saveDrawings) {
      ElMessage.warning('绘图工具未准备就绪')
      return { success: false, message: '绘图工具未准备就绪' }
    }
    
    try {
      return drawHook.value.saveDrawings()
    } catch (error) {
      console.error('保存绘图失败:', error)
      ElMessage.error('保存绘图失败: ' + error.message)
      return { success: false, message: error.message }
    }
  }
  
  /**
   * 加载绘制
   */
  function loadDrawings() {
    if (!drawHook.value || !drawHook.value.loadDrawings) {
      ElMessage.warning('绘图工具未准备就绪')
      return { success: false, message: '绘图工具未准备就绪' }
    }
    
    try {
      return drawHook.value.loadDrawings()
    } catch (error) {
      console.error('加载绘图失败:', error)
      ElMessage.error('加载绘图失败: ' + error.message)
      return { success: false, message: error.message }
    }
  }
  
  /**
   * 清理交互
   */
  function clearInteractions() {
    if (drawHook.value && drawHook.value.clearInteractions) {
      try {
        drawHook.value.clearInteractions()
      } catch (error) {
        console.error('清理交互失败:', error)
      }
    }
  }
  
  return {
    // 状态
    isDrawing,
    isIconDrawing,
    isDelete,
    isModify,
    selectedShape,
    selectedIcon,
    scale,
    drawHook,
    isMapReady,
    
    // 选项
    shapeOptions,
    iconOptions,
    
    // 计算属性
    canSelectShape,
    canDraw,
    
    // 方法
    setDrawHook,
    setMapReady,
    setDrawing,
    setDelete,
    setModify,
    setSelectedShape,
    setSelectedIcon,
    adjustIconScale,
    startDrawShape,
    startDrawIcon,
    toggleDelete,
    toggleModify,
    saveDrawings,
    loadDrawings,
    clearInteractions
  }
}) 